const { contextBridge, ipcRenderer } = require('electron')
const os = require('os')
const spawn = require('child_process').spawn
const Store = require('electron-store')

const store = new Store()

// Expose protected methods that allow the renderer process to use
// the ipcRenderer without exposing the entire object
contextBridge.exposeInMainWorld('ipcRenderer', {
    send: (channel, data) => {
        // whitelist channels
        const validChannels = ['saveInstruments', 'contextMenu']
        if (validChannels.includes(channel)) {
            ipcRenderer.send(channel, data)
        }
    },
    sendSync: (channel, data, callback) => {
        // whitelist channels
        const validChannels = ['zoomFactor']
        if (validChannels.includes(channel)) {
            const result = ipcRenderer.sendSync(channel, data)
            callback && callback(result)
        }
    }
})


contextBridge.exposeInMainWorld('API', {
    listSystemInfos(callback) {
        const infos = {
            hostname: os.hostname(),
            uptime: os.uptime(),
            release: os.release(),
            networkInterfaces: os.networkInterfaces(),
            cpus: os.cpus()
        }
        const prc = spawn('free', [])
        prc.stdout.on('data', (data) => {
            const mems = data.toString().split(/\n/g)[1].split(/\s+/)
            const swaps = data.toString().split(/\n/g)[2].split(/\s+/)
            callback && callback(mems, swaps)
        })
        return infos
    },
    listInstruments(callback) {
        const instruments = store.get('instruments')
        callback && callback(instruments)
    }
})